package com.wyf.sentineldemo2.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.wyf.sentineldemo2.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class HelloController {
    private static final String RESOURCE_NAME = "hello";
    private static final String USER_RESOURCE_NAME = "user";
    private static final String DEGRADE_RESOURCE_NAME = "degrade";

    @RequestMapping("/hello")
    public String hello() {

        Entry entry = null;
        try {
            // sentinel针对资源进行限制的
            entry = SphU.entry(RESOURCE_NAME);
            // 被保护的业务逻辑
            String str = "hello world";
            log.info("======" + str + "======");
            return str;
        } catch (BlockException e1) {
            // 资源访问组织，被限流或被降级
            // 进行相应的处理操作
            log.info("block");
            return "被流控了！";
        } catch (Exception exception) {
            Tracer.traceEntry(exception, entry);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return null;
    }

    /**
     * 定义规则
     * <p>
     * spring的初始方法
     */
    @PostConstruct // <bean init-method=""
    private static void initFlowRules() {
        // 流控规则
        List<FlowRule> rules = new ArrayList<>();

        // 流控
        FlowRule rule = new FlowRule();
        // 设置受保护的资源
        rule.setResource(RESOURCE_NAME);
        // 设置流控规则QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置被保护的资源阈值
        // set limit QPS to 20
        rule.setCount(1);
        rules.add(rule);

        // 流控
        FlowRule rule2 = new FlowRule();
        // 设置受保护的资源
        rule2.setResource(USER_RESOURCE_NAME);
        // 设置流控规则QPS
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置被保护的资源阈值
        // set limit QPS to 20
        rule2.setCount(1);
        rules.add(rule2);

        // 加载配置好的规则
        FlowRuleManager.loadRules(rules);
    }

    @PostConstruct // 初始化
    public void initDegradeRule() {
        // 降级规则 异常
        List<DegradeRule> degradeRules = new ArrayList<>();
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource(DEGRADE_RESOURCE_NAME);
        // 设置规则方式
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        // 异常数 2
        degradeRule.setCount(2);
        // 触发熔断的最小请求书
        degradeRule.setMinRequestAmount(2);
        // 统计时长  单位：ms
        degradeRule.setStatIntervalMs(60 * 1000); // 时间太短不太好测
        // 熔断时长
        degradeRule.setTimeWindow(10);

        degradeRules.add(degradeRule);
        DegradeRuleManager.loadRules(degradeRules);
    }

    @RequestMapping("/degrade")
    @SentinelResource(value = DEGRADE_RESOURCE_NAME, entryType = EntryType.IN, blockHandler = "blockHandlerForFb")
    public User degrade(String id) throws InterruptedException {
        throw new RuntimeException("异常");
    }

    public User blockHandlerForFb(String id, BlockException ex) {
        return new User("wangyf");
    }

    /**
     * @SentinelResource 改善接口中资源定义和被流控降级后的处理方法
     * 使用方法
     *   1.添加依赖
     *   2.配置bean SentinelResourceAspect
     *   value 定义资源
     *   blockHandler 设置被流控降级后的处理方法（默认该方法必须声明在同一个类中）
     *     如果不想在同一个类中，设置blockHandlerClass，方法必须是static
     *   fallback 当接口出现异常，可以交给fallback指定的方法来处理
     *     blockHandler 和 fallback同志指定的话，blockHandler优先级更高
     *   exceptionToIgnore 排除哪些异常不处理
     * @param id
     * @return
     */
    @RequestMapping("/user")
    @SentinelResource(value = USER_RESOURCE_NAME, fallback = "fallbackHandlerForGetUser"
            , blockHandler = "blockHandlerForGetUser")
    public User getUser(String id) {
        int a = 1 / 0;
        return new User("wangyf");
    }

    public User fallbackHandlerForGetUser(String id, Throwable e) {
        e.printStackTrace();
        return new User("异常处理");
    }

    /**
     * 注意：
     *   1.一定要是public
     *   2.返回值一定要和原方法保证一致
     *   3.包含原方法的参数，可以在参数的最后添加 BlockException，可以区分是什么规则的处理方法
     * @param id
     * @param e
     * @return
     */
    public User blockHandlerForGetUser(String id, BlockException e) {
        e.printStackTrace();
        return new User("流控！！");
    }
}
